//
//  NetworkTools+Extension.swift
//  FWSinaWeibo
//
//  Created by 范伟 on 16/2/25.
//  Copyright © 2016年 FanWei. All rights reserved.
//

import Foundation

extension NetworkTools {
    /// 返回身份验证 URL
    /**
    1. 没有参数，只有返回值的函数，在调用的时候，有一个 ()
    2. 使用计算型属性，直接返回某一个类型的结果
    3. 计算型属性不能接参数
    4. 阅读的语义会更好！
    */
    var oauthUrl: NSURL {
        let url = NSURL(string: "https://api.weibo.com/oauth2/authorize?client_id=\(appkey)&redirect_uri=\(redirectUri)")
        return url!
    }
    
    /**
     加载令牌成功之后，立即网络请求用户账户信息
     
     - parameter code:     授权码
     - parameter finished: 网络完成之后的回调
     */
    func loadAccessToken(code: String, finished: (result: [String: AnyObject]?) -> ()) {
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = ["client_id": appkey,
            "client_secret": appSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": redirectUri
        ]
        request(.POST, urlString: url, parameters: params) {[weak self] (result) -> () in
            guard let result = result,
                let accessToken = result["access_token"] as? String,
                let uid = result["uid"] as? String else {
                    print("数据格式不正确")
                    //一定要完成回调，通知调用方请求失败
                    finished(result: nil)
                    return
            }
            self?.loadUserInformation(accessToken, uid: uid) { userDict in
                //合并字典
                guard var userDict = userDict else {
                    print("用户数据加载失败！")
                    finished(result: nil)
                    return
                }
                for (k, v) in result {
                    userDict[k] = v
                }
                finished(result: userDict)
            }
        }
    }
}
